/*
 * Copyright (c) 2011  Cristian Constantin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.quizio.security;

import com.quizio.dao.UserDao;
import com.quizio.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Cristian Constantin
 * @since 01.12.2010
 */
@Service
@Transactional(readOnly = true)
public class DefaultSecurityManager implements SecurityManager {

    @Autowired
    UserDao userDao;

    @Autowired
    PasswordEncoder passwordEncoder;

    public User getUserByUsername(String username) {
        return userDao.getUserByUsername(username);
    }

    @Transactional(readOnly = false)
    public void createAccount(User user) {
        user.setDisabled(false);
        user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
        userDao.saveOrUpdate(user);
    }

    @Override
    public User getCurrentAuthenticatedUser() {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            return (User) principal;
        } else {
            String username = principal.toString();
            return getUserByUsername(username);
        }
    }
}
